#include "modbus_register.h"

// 主处理函数：分发读写请求到对应模块
bool modbus_register_handler(uint16_t address, uint16_t* value, bool is_write) {
    // 地址合法性校验
    if (address > MODBUS_REG_MAX_ADDR || value == NULL) {
        return false;
    }

    // 按模块分发请求
    if (address >= REG_SOLD_OUT_STATUS && address <= REG_DEVICE_MODE) {
        // 首页模块
        if (is_write) modbus_home_set(address, *value);
        else *value = modbus_home_get(address);
    } 
    else if ((address >= REG_JAM_ING_SET_BASE && address <= REG_TOPPING_ING_SET_BASE + 2) || 
             address == REG_AUTO_PRODUCTION) {
        // 生产模块（自动制作）
        if (is_write) modbus_production_set(address, *value);
        else *value = modbus_production_get(address);
    }
    else if (address >= REG_CUP_PICKUP_POS_BASE && address <= REG_MANUAL_CUP_DISP) {
        // 冰淇淋设置模块 (0x000A-0x0011)
        if (is_write) modbus_ice_cream_set(address, *value);
        else *value = modbus_ice_cream_get(address);
    }
    else if (address >= REG_TOPPING1_POS_BASE && address <= REG_TOPPING3_REMAIN_COUNT) {
        // 顶料位置模块 (0x0012-0x001A)
        if (is_write) modbus_topping_set(address, *value);
        else *value = modbus_topping_get(address);
    }
    else if (address >= REG_JAM1_POS_BASE && address <= REG_JAM3_REMAIN_COUNT) {
        // 果酱设置模块 (0x001B-0x0023)
        if (is_write) modbus_jam_set(address, *value);
        else *value = modbus_jam_get(address);
    } else if(address>= REG_TOTAL_CUP_START && address <= REG_TOP3_DISP_COUNT)
    {
        if(!is_write)
        {
          *value = modbus_statistics_get(address); 
          return true;
        }

    }
    else if ((address >= REG_TOTAL_CUP_START && address <= REG_TOTAL_CUP_COUNT) || 
             address == REG_X_AXIS_ORIGIN || address == REG_MAIN_COMPRESSOR) {
        // IO与统计模块
        if (is_write) modbus_io_set(address, *value);
        else *value = modbus_io_get(address);
    }
    else {
        // 未实现的寄存器
        return false;
    }

    return true;
}
    
   